#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import requests
import os,re,IPy,time

def CDNlist(ipC):
    Default=False
    CDN = open('CDN_IPlist.txt').read().split('\n')
    for x in CDN:
        CDN_ip=IPy.IP(x)
        boolIP=(ipC in CDN_ip)
        Default=(Default or boolIP)
    return Default

def kuaishou(url,DATA):
    HEAD = {'X-REQUESTID': '1382677768', 'User-Agent': 'kwai-android', 'Connection': 'keep-alive',
            'Accept-Language': 'zh-cn', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': '145',
            'Accept-Encoding': 'gzip', 'Pragma': 'no-cache'}
    try:
        r = requests.post(url, headers=HEAD, data=DATA)
        kuaishou_R = r.json()['feeds'][0]['main_mv_urls'][0]['cdn']
        video = r.json()['feeds'][0]['main_mv_urls'][0]['url']
        return kuaishou_R,video
    except:
        return "打开失败","打开失败"



def dnsR(domian):
    ns=os.popen('nslookup % s ' % domian).read()
    if ns.find('Name:') == -1:
        return []
    else:
        ns=ns[ns.find('Name:'):]
        ip = re.findall('\d+\.\d+\.\d+\.\d+', ns)
        return ip

def main(url,DATA):
    kuaishou_Domian,video = kuaishou(url,DATA)  # 获取cdn域名
    kuaishou_IP = dnsR(kuaishou_Domian)  # 解析IP
    if len(kuaishou_IP) == 0:
        flag = "无解析结果"
    else:
        if CDNlist(kuaishou_IP[0]):
            # print(miaopai_ip)
            flag = '网内'
        else:
            flag = '出网'
    return (video, flag, "<br>".join(kuaishou_IP))

if __name__ == '__main__':
    sig='1f7dd1678c42cb47f75ea043ecf14cec'
    DATA = {'type': '7', 'page': '5', 'coldStart': 'false', 'count': '20', 'pv': 'false', 'id': '8',
            'refreshTimes': '7', 'pcursor': '1', 'client_key': '3c2cd3f3', 'os': 'android',
            'sig': sig}
    url = 'http://180.186.38.200/rest/n/feed/hot?mod=samsung(SM-G9250)&lon=120.096915&country_code=CN&did=ANDROID_a5f6071cd589fc61&app=0&net=WIFI&oc=UNKNOWN&ud=0&c=MYAPP_CPD&sys=ANDROID_6.0.1&appver=5.2.1.4701&ftt=&language=zh-cn&lat=30.26885&ver=5.2'

    for i in range(10):
        t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        res = main(url, DATA)
        print('%s\t%s\t%s\n' % res)
        fLog=open('/var/www/html/short_video/%sShortVideoLog.txt'% time.strftime("%Y-%m-%d", time.localtime()),'a' )
        fLog.write(t+'\t快手\t%s\t%s\t%s\n' % res)
        fLog.close()